<template>
	<yd-layout id='courseAudioDetail' class=''>
		<!--@canplay='canplay' 用这个可能会有1秒的延迟-->
			<!--controls="controls"-->
		<template v-if="dataObj.url">
			<audio ref='audioRef' id='audioId'  @playing="audioPlaying"  @ended='audioEnded'  @pause="pauseAudio" @play='playAudio' @canplaythrough='canplaythrough'   class="audio_audio">
				<source :src="dataObj.url"/>
				<source :src="dataObj.url"/> 您的浏览器不支持 audio 元素。
			</audio>
		</template>
		<div class="header">
			<div class="header_img" :class="false?'header_2':''">
				<img class="header_video_img_1 img_animate" :style="videoStyle" src="../../assets/audioDetail_5.png" />
				<img v-if="mp3Play" class="header_video_img_2" src="../../assets/audioDetail_7.png" />
				<img v-else class="header_video_img_2" src="../../assets/audioDetail_6.png" />
			</div>
			
			<div class="header_video">
				<img @click="playVideo" v-if="!mp3Play" class="auto_img" src="../../assets/audioDetail_3.png" alt="" />
				<img @click="playVideo" v-else class="auto_img" src="../../assets/audioDetail_2.png" alt="" />
				<div class="auto_right">
					<div class="auto_time_1">{{audioPlayTime}}</div>
					<div class="auto_xian">
						<!--:key='dataObj.url'-->
						<van-slider :key='dataObj.url' :disabled='disabled' v-model="palyVal" bar-height="4px" active-color="#DCBBC9" @change="onChange" @input='onInput' />
					</div>
					<div class="auto_time_2">{{audioAllTime}}</div>
				</div>
			</div>
		</div>
		<div class="content">
			<div class="hader_title">
				<div class="title c_size_34_48">{{dataObj.title}}</div>
				<div class="label">
					<div class="label_people">{{dataObj.watch_count}}次学习</div>
					<!--!$route.query.collect-->
					<template v-if="false">
						<div v-if='dataObj.collected==1'  style='background: #999999;' class="btn" @click="collect(1)">已收藏</div>
						<div  v-else class="btn" @click="collect">收藏</div>
					</template>
				</div>
			</div>
			<!--<div>{{cscccc}}-{{palyVal}}-{{endTime}}</div>-->
			<template v-if="palyList.length>0">
				<div class="play_list">
					<div class="play_list_title c_size_34_48">播放列表</div>
					<div class="paly_list_item_f_f" ref='playListRef'>
						<div class="paly_list_item_f"  :style="playListStyle">
							<div ref='playListItemRef' @click="refresh(item,index)" v-for="item,index in palyList" class="width_paly_list_item">
								<div  :class="item.id==dataObj.id?'paly_active':''" class="paly_list_item" >
									<div  class="paly_list_item_content c_text_ellipsis_2">{{item.title}}</div>
									<div v-if="item.id==dataObj.id" class="paly_list_item_label">正在播</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</template>
			<div class="student_list">
				<div class="play_list_title c_size_34_48">学习感悟</div>
				<div class="student_label">收听课程后，写下你的心得与收获</div>
				<div class="list_item">
					<yd-infinitescroll v-show='commentList.length>0' :callback="getCommetnList" ref="infinitescrollDemo">
						<StudentShareList :audioType='false'  slot="list"  :dataList='commentList'></StudentShareList>
						<!-- 数据全部加载完毕显示 -->
				        <span slot="doneTip">没有更多数据了~~</span>
				
				        <!-- 加载中提示，不指定，将显示默认加载中图标 -->
				        <!--<img slot="loadingTip" src="path/img/loading.svg"/>-->
					</yd-infinitescroll>
					<div v-if='commentList.length==0' class="no_list">暂无内容</div>
				</div>
			</div>
		</div>
		<div slot='bottom' class="study_bottom_f">
			<div @click="writeShare" class="study_bottom">写写学习感悟~</div>
			<!--<input type="text" />-->
		</div>
		<yd-popup v-model="showWrite" position="bottom" height="3.82rem">
			<div  class='pop_share'>
				<div class="pop_header">
					<img @click="showWrite=false" class="pop_header_img" src="../../assets/audioDetail_8.png" alt="" />
					<div class="pop_header_btn" @click="sendShare" :style="{color:(textareaVal+'').length>0?'#DCBBC9':'#999999'}">发送</div>
				</div>
				<div class="textarea">
					<textarea @blur="closeShare" placeholder="写写学习感悟~" v-model.trim="textareaVal" ref='textareaRef' maxlength="150" name="" rows="" cols=""></textarea>
					<div class="text_num">{{(textareaVal+'').length}}/150</div>
				</div>
        		<!--<yd-textarea  class="textarea"   placeholder="写写学习感悟~" maxlength="150"></yd-textarea>-->
			</div>
		</yd-popup>
		<yd-backtop></yd-backtop>
	</yd-layout>
</template>

<script>
	import { Slider } from 'vant';
	import StudentShareList from '../../components/StudentShareList/StudentShareList.vue'
	import { InfiniteScroll } from 'vue-ydui/dist/lib.rem/infinitescroll';
	import {BackTop} from 'vue-ydui/dist/lib.rem/backtop';
	import {Popup} from 'vue-ydui/dist/lib.rem/popup';
	let setTime = ''
	export default {
		components: {
			[Slider.name]:Slider,
			[StudentShareList.name]:StudentShareList,
			[InfiniteScroll.name]: InfiniteScroll,
			[BackTop.name]:BackTop,
			[Popup.name]: Popup,
		},
		data() {
			return {
				commentList:[],
				pageNum:1,
				pageCount:10,
				dataObj:{},
				playListStyle:{
					width:''
				},
				dataObj:{},
				palyList:[],
				videoId:'',
				
				palyVal: 0,
				mp3Play: true,
				audioAllTime: '00:00', //总时长
				audioPlayTime: '00:00', //播放时间
				palyTime: 0,
				disabled: true,
				audioObj:{},
				videoStyle:{
					animationPlayState:'paused'
				},
				oldCurrentTime:0,
				num:1,
				henxianNum:1,
				showWrite:false,
				textareaVal:'',
				ListWidth:0,
				cscccc:0,
				endTime:0,
				
				mineObj:{},
			}
		},
		created() {

		},
		watch: {

		},
		computed: {

		},
		destroyed (){
			clearInterval(setTime)
		},
		beforeDestroy(){
			if(!this.mp3Play){
				this.endTime = this.palyTime
				this.$root.submitEvent({
					kind:100,
					lastFlg:true,
					position:this.endTime,
				})
			}
		},
		mounted() {
			document.title = '播放课程'
			this.videoId=this.$route.query.id
			this.getMine();
			this.getVideoDetail()
			this.getCommetnList()
		},
		methods: {
			closeShare(){
				setTimeout(function() {
					var scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
					window.scrollTo(0, Math.max(scrollHeight - 0.01, 0));
				}, 150);
				setTimeout(()=>{
					this.showWrite=false
				},250)
			},
			sendShare(){
				if(this.textareaVal){
					this.$root.ajax({
						name: 'comment/doComment',
						params: {
							kind: 100,
							oid:this.videoId,
							content:this.textareaVal,
						}
					}).then((d) => {
						this.showWrite=false;
		                this.textareaVal = ''
		                    	
		               	this.pageNum=1;
						this.pageCount=10;
						this.commentList=[]
						this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.reInit');
						this.getCommetnList(true)
						this.$dialog.toast({
		                    mes: '评论成功',
		                    timeout: 1500,
		                    icon: 'success',
		                    callback: () => {
		                    	
		                    	
		                    }
		                });
					})
				}else{
					this.$dialog.toast({
	                    mes: '请输入学习感悟~',
	                    timeout: 1500,
	                });
				}
			},
			writeShare(){
//				this.$router.push({name:'audioStudentShare',query:{oid:this.videoId}})
				this.showWrite=true
				this.$refs.textareaRef.focus();
			},
			onChange(val) {
				let audio = this.$refs.audioRef
				let time = this.$refs.audioRef.duration
				let nowTime = parseInt(time * (val / 100))
				this.audioPlayTime = (parseInt(nowTime / 60) >= 10 ? parseInt(nowTime / 60) : '0' + parseInt(nowTime / 60)) + ':' +
						(parseInt(nowTime % 60) >= 10 ? parseInt(nowTime % 60) : '0' + parseInt(nowTime % 60))
				if(setTime){
					clearInterval(setTime)
				}
				setTime = ''
				if(val >= 100) {
					this.henxianNum = 2
					this.mp3Play = true
					audio.pause()
					this.palyVal = val
					this.palyTime = time
					this.videoStyle={
							animationPlayState:'paused'
						}
					this.audioPlayTime = (parseInt(this.palyTime / 60) >= 10 ? parseInt(this.palyTime / 60) : '0' + parseInt(this.palyTime / 60)) + ':' +
						(parseInt(this.palyTime % 60) >= 10 ? parseInt(this.palyTime % 60) : '0' + parseInt(this.palyTime % 60))
				} else {
					this.palyTime = parseInt(time * (val / 100))
					
					audio.play()
					this.mp3Play = false
					audio.currentTime = this.palyTime; //减少误差
					this.videoStyle={
						animationPlayState:'running'
					}
				}

			},
			//拖动的时候触发
			onInput(val) { 
				if(val>0){
					this.henxianNum = 1
				}else{
					this.henxianNum = 2
				}
				this.videoStyle={
					animationPlayState:'paused'
				}
				this.mp3Play = true
				if(setTime) {
					let audio = this.$refs.audioRef
					audio.pause() 
					clearInterval(setTime)
					setTime = ''
				}
			},
			//音频已经准备好
			canplaythrough() {
				let time = this.$refs.audioRef.duration
				var ua = navigator.userAgent;
				//有时候因为那个Interval延迟，这里在清除一次，哎
				
				if(/iPhone|iPad|iPod/.test(ua)&&this.$root.isPcOS() == 'Phone') {
					//'ios'
					if(setTime){
						clearInterval(setTime)
						setTime = ''
					}
					if(!this.mp3Play) {
						if(time > 0) {
							//this.disabled = false;
						}
						let min = parseInt(time / 60) >= 10 ? parseInt(time / 60) : '0' + parseInt(time / 60)
						let s = parseInt(time % 60) >= 10 ? parseInt(time % 60) : '0' + parseInt(time % 60)
						let strTime = min + ':' + s
						this.audioAllTime = strTime
						
						this.palyTimeFun(time)
					}
				} else {
					
					if(time > 0) {
						//this.disabled = false;
					}
					if(time>=0){
						let min = parseInt(time / 60) >= 10 ? parseInt(time / 60) : '0' + parseInt(time / 60)
						let s = parseInt(time % 60) >= 10 ? parseInt(time % 60) : '0' + parseInt(time % 60)
						let strTime = min + ':' + s
						this.audioAllTime = strTime
					}
				}
			},
			//自己的时间处理
			palyTimeFun(time,flg) {
				//!setTime 不然手速太快回出问题
				
				if(!this.mp3Play && time&&(!setTime)) {
					setTime = setInterval(()=>{
						//this.cscccc = this.palyVal 
						//表示没有网络的时候  还有一种可能是视频还差0.5毫秒的时候，但是还在走
						if((this.oldCurrentTime == this.audioObj.currentTime)&& (this.oldCurrentTime!=time) ){
							clearInterval(setTime)
							setTime = ''
							this.henxianNum = 1
							this.num = 2
						}else{
							this.num = 1
							this.oldCurrentTime = this.audioObj.currentTime
							this.palyTime = this.audioObj.currentTime
							this.palyTime  = Math.ceil(this.palyTime)
							this.palyTime  = parseInt(this.palyTime)
						}
						//清除循环
						if(this.oldCurrentTime >= parseInt(time)){
							clearInterval(setTime)
							setTime = ''
						}else{
							this.audioPlayTime = (parseInt(this.palyTime / 60) >= 10 ? parseInt(this.palyTime / 60) : '0' + parseInt(this.palyTime / 60)) + ':' +
							(parseInt(this.palyTime % 60) >= 10 ? parseInt(this.palyTime % 60) : '0' + parseInt(this.palyTime % 60))
							if(this.henxianNum!=1){
								this.palyVal = parseFloat(Math.ceil(this.palyTime / time * 100))
							}
							this.henxianNum++
							//this.cscccc ++
						}
					},1000)
				}

			},
			audioEnded(){
				clearInterval(setTime);
				setTime = ''
				this.mp3Play = true
				this.palyVal = 100
				this.palyTime = 0
				this.audioObj.loop = false
				this.audioObj.pause()
				
				let time = this.audioObj.duration
				this.audioPlayTime = (time / 60) >= 10 ? parseInt(time / 60) : '0' + parseInt((time / 60)) + ':' +
					(parseInt(time % 60) >= 10 ? parseInt(time % 60) : '0' + parseInt(time % 60))
			},
			audioPlaying(){
				this.videoStyle={
					animationPlayState:'running'
				}
				if(this.num  == 2){
					this.palyTimeFun(this.audioObj.duration)
				}
			},
			pauseAudio(){
				this.videoStyle={
					animationPlayState:'paused'
				}
			},
			playAudio(){
				let time = this.audioObj.duration
				this.cscccc = time
				
				
				if(time&&((time+'').indexOf('finity'))<0){
					if(!this.mp3Play) {
						this.disabled = false;
						setTime = ''
						this.audioObj.currentTime = this.palyTime ; //减少误差
						this.palyTimeFun(time,true)
						this.disabled = false;
					}
				}else{
					this.audioObj.pause()
					this.mp3Play = true
					clearInterval(setTime)
					setTime = ''
					this.videoStyle={
						animationPlayState:'paused'
					}
				}
				
			},
			//播放
			playVideo() {
					if(this.mineObj.member_status != 1) {
						//弹出开通会员框
						this.$dialog.confirm({
							title: '温馨提示',
							mes: '该场直播需要开通会员权限才能观看',
							opts: [{
									txt: '取消',
									color: '#999999',
									callback: () => {
								},
							},
							{
								txt: '开通会员',
								color: '#F5AB16',
								callback: () => {
									this.$router.push({
											name: 'vipOpen'
									})
								}
							},
						]
					});
					return
				}

				let audio = this.$refs.audioRef
				let time = this.$refs.audioRef.duration
				if(this.palyTime >= time) {
					this.audioPlayTime ='00:00'
					this.palyVal = 0
					this.mp3Play = false
					this.palyTime = 0;
					audio.play()
				} else {
					if(this.mp3Play) {
						if(this.palyTime === 0){
							this.audioPlayTime = '00:00'
						}
						this.henxianNum = 2
						audio.play()
						//播放
						this.mp3Play = false
						
						
						this.$root.id = this.videoId
						this.$root.uuid = (parseInt((parseInt(new Date()-0))/1000))+''+(this.$root.userInfo.me.id||0)
						this.$root.submitEvent({
							kind:100,
							position:audio.currentTime,
						})
						
						this.$store.commit({
							type:'setDataEvent',
							data:{
								kind:100,
								oid:this.$route.query.id,
								uuid:this.$root.uuid,
								uid:this.$root.userInfo&&(JSON.stringify(this.$root.userInfo)!='{}')?this.$root.userInfo.me.id:0,
								position:audio.currentTime
							}
						})
						
						this.videoStyle={
							animationPlayState:'running'
						}
						
					} else {
						//暂停
						this.mp3Play = true
						audio.pause()
						clearInterval(setTime)
						setTime = ''
						this.videoStyle={
							animationPlayState:'paused'
						}
						
						this.$root.id = this.videoId
						this.$root.submitEvent({
							kind:100,
							lastFlg:true,
							position:audio.currentTime
						})
					}
				}

			},
			//重新加载其他的
			refresh(item,index){
				//this.$refs.playListRef.scrollLeft = (index * this.ListWidth) 
				this.endTime = this.palyTime
				this.videoId=item.id
				this.$root.id = this.videoId
					this.$root.submitEvent({
					kind:100,
					lastFlg:true,
					position:this.endTime
				})
				
				this.getVideoDetail(true)
				this.disabled = true
				this.pageNum=1;
				this.pageCount=10;
				this.commentList=[]
				this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.reInit');
				this.getCommetnList()
			},
			getCommetnList(flg){
				this.$root.ajax({
					name: 'comment/lst',
					type:'get',
					closeAllLoading:flg?true:false,
					params: {
						page:this.pageNum,
						count:this.pageCount,
						kind:100,
						oid:this.videoId
					}
				}).then((d) => {
					let date = new Date()
					for(let a = 0 ;a<d.data.comment_list.length;a++){
						//刚刚
						if(date-d.data.comment_list[a].create_time*1000<60*1000){  //60s
							d.data.comment_list[a].newTime = '刚刚'
						}else if(date-d.data.comment_list[a].create_time*1000<5*60*1000){ //5min
							d.data.comment_list[a].newTime = '5分钟之内'
						}else if(date-d.data.comment_list[a].create_time*1000<30*60*1000){ //30min
							d.data.comment_list[a].newTime = '30分钟之内'
						}else if(date-d.data.comment_list[a].create_time*1000<3*60*60*1000){ //3h
							d.data.comment_list[a].newTime = '3小时之内'
						}else if(date-d.data.comment_list[a].create_time*1000<24*60*60*1000){ //24
							d.data.comment_list[a].newTime = '24小时之内'
						}else {
							let plDate = new Date(d.data.comment_list[a].create_time*1000)
							let month = plDate.getMonth()
							let day = plDate.getDate()
							if(date.getFullYear() == plDate.getFullYear()){
								d.data.comment_list[a].newTime = (month+1 < 10 ? '0' + (month + 1) : (month + 1)) + '-' + (day < 10 ? '0' + day : day)
							}else{
								d.data.comment_list[a].newTime = plDate.getFullYear() + '-' + (month+1 < 10 ? '0' + (month + 1) : (month + 1)) + '-' + (day < 10 ? '0' + day : day) 
							}
						}
					}
					
					this.commentList = [...this.commentList, ...d.data.comment_list] ;
					
                    if (this.commentList.length >= d.data.comment_total ) {
                        /* 所有数据加载完毕 */
                        this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
                        return;
                    }

                    /* 单次请求数据完毕 */
                    this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.finishLoad');

                    this.pageNum++;
				})
			},
			//请求视频详情
			getVideoDetail(audioFlg){
				this.$root.ajax({
					name: 'hqc/video',
					type:'get',
					params: {
						id:this.videoId
					}
				}).then((d) => {
					if(audioFlg){
						let audio = this.$refs.audioRef
						let time = this.$refs.audioRef.duration
						audio.src = d.data.video.url
						this.audioPlayTime = '00:00'
						this.audioAllTime = '00:00'
						this.palyVal = 0
						this.mp3Play = true
						this.palyTime = 0;
						this.oldCurrentTime = 0
						this.num=0
				
						if(setTime){
							clearInterval(setTime)
						}
						setTime = ''
						this.videoStyle={
							animationPlayState:'paused'
						}
						this.henxianNum = 2
						//audio.play()
						//this.palyTimeFun(time)
					}
					//d.data.video.url = 'https://www.runoob.com/try/demo_source/movie.mp4'
					//这里的音频m3u8要抽风
					this.dataObj=Object.assign({},this.dataObj,d.data.video);
					this.palyList = d.data.video_list;
					
					this.$nextTick(()=>{
						this.audioObj = this.$refs.audioRef;
					})
					let indexNum = 0;
					for(let a = 0 ;a<this.palyList.length;a++){
						if(this.palyList[a].id == this.dataObj.id){
							indexNum = a
							break
						}
					}
					this.$nextTick(()=>{
						if(this.palyList.length>2){
							this.playListStyle={
								width:(this.$refs.playListItemRef[0].offsetWidth+this.$refs.playListItemRef[1].offsetWidth*(this.palyList.length-1) +1)+'px'
							}
							this.$nextTick(()=>{
								this.ListWidth = this.$refs.playListItemRef[1].offsetWidth
								this.$refs.playListRef.scrollLeft = (indexNum * this.ListWidth) 
							})
						}else if(this.palyList.length==1){
							this.playListStyle={
								width:(this.$refs.playListItemRef[0].offsetWidth )+'px'
							}
						}
					})
					
					//分享
					if(this.$root.isWeiXin()){
						//分享
						let query = '';
						if(this.$root.config.channel){
						 	query = `params=channelDY2FGoldUrlStrDY${this.$route.name}FGkeyNumDY1FGparamsKey1DYidFGparamsVal1DY${this.videoId}`
						}else{
						 	query = `params=oldUrlStrDY${this.$route.name}FGkeyNumDY1FGparamsKey1DYidFGparamsVal1DY${this.videoId}`
						}
						this.$root.wxShare({
							d:this.dataObj,//分享对象，题目等{title:'',title-img:''}
							query: query,//参数
							desc:`${this.dataObj.watch_count}次学习`//分享详情
						})
					}
				})
			},
			//获取个人信息
			getMine(){
				this.$root.ajax({
					name:'my',
					params:{}
				}).then((d)=>{
					this.mineObj=Object.assign({},this.mineObj,d.data)
				})
			},
		}
	}
</script>

<style lang="scss">
	@import './courseAudioDetail.scss';
</style>